#include <am.h>
#include <nemu.h>

#define SYNC_ADDR (VGACTL_ADDR + 4)

void __am_gpu_init() {
	int i;
	int w = 400;
	int h = 300;
	uint32_t *fb = (uint32_t *)(uintptr_t)FB_ADDR;
	for(i = 0; i< w*h; i++)fb[i] = i;
	outl(SYNC_ADDR,1);
}

void __am_gpu_config(AM_GPU_CONFIG_T *cfg) {
  *cfg = (AM_GPU_CONFIG_T) {
    .present = true, .has_accel = false,
    .width = 400, .height = 300,
    .vmemsz = 0
  };
}

void __am_gpu_fbdraw(AM_GPU_FBDRAW_T *ctl) {
  if (ctl->sync) {
    outl(SYNC_ADDR, 1);
  }
  int x = ctl->x, y = ctl->y, w = ctl->w, h = ctl->h;
  int a,b;
  uint32_t *myfb = (uint32_t *)(uintptr_t)ctl->pixels;
  uint32_t *fb = (uint32_t *)(uintptr_t)FB_ADDR;
  if (w == 0 || h == 0) return;
  else
  {
    for(a = 0; a < w; a++){
      for(b = 0; b < h; b++){
        fb[x+a+(y+b)*400] = myfb[a+b*w];
      }
    }
  }

}

/*
void __am_gpu_fbdraw(AM_GPU_FBDRAW_T *ctl) {
  int x = ctl->x, y = ctl->y, w = ctl->w, h = ctl->h;
  if (w == 0 || h == 0) return;
  feclearexcept(-1);
  SDL_Surface *s = SDL_CreateRGBSurfaceFrom(ctl->pixels, w, h, 32, w * sizeof(uint32_t),
      RMASK, GMASK, BMASK, AMASK);
  SDL_Rect rect = { .x = x, .y = y };
  SDL_BlitSurface(s, NULL, surface, &rect);
  SDL_FreeSurface(s);
}

*/

void __am_gpu_status(AM_GPU_STATUS_T *status) {
  status->ready = true;
}
